<?php

namespace App\Services\Auth;

use App\Services\ServiceTrait;
use App\Models\Agency\Auth\UserConfig;
use App\Models\Agency\Config\Language;
use App\Models\Agency\Config\Timezone;
use App\Models\Agency\Config\Server;
use App\Models\Game\Platform\Org;

class UserConfigService
{
    use ServiceTrait;

    /**
     * 个人设置【菜单宽度】
     *
     * @param \Illuminate\Contracts\Auth\Authenticatable $user
     * @param int $layoutAsideWidth
     * @return \App\Models\Agency\Auth\UserConfig
     * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
     */
    public function setLayoutAsideWidth($user, $layoutAsideWidth)
    {
        $config = UserConfig::firstOrNew(['user_id' => $user->id]);

        $config->fill(['layout_aside_width' => $layoutAsideWidth])->save();

        return $config;
    }

    /**
     * 个人设置【语言】
     *
     * @param \Illuminate\Contracts\Auth\Authenticatable $user
     * @param string $lang
     * @return \App\Models\Agency\Auth\UserConfig
     * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
     */
    public function setLanguage($user, $lang)
    {
        $language = Language::where('lang', $lang)->firstOrFail();

        $config = UserConfig::firstOrNew(['user_id' => $user->id]);

        $config->fill(['language_lang' => $language->lang])->save();

        return $config;
    }

    /**
     * 个人设置【时区】
     *
     * @param \Illuminate\Contracts\Auth\Authenticatable $user
     * @param string $timezone
     * @return \App\Models\Agency\Auth\UserConfig
     * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
     */
    public function setTimezone($user, $timezone)
    {
        $config = UserConfig::firstOrNew(['user_id' => $user->id]);

        $config->fill(['timezone' => $timezone])->save();

        return $config;
    }

    /**
     * 个人设置【服务器】
     *
     * @param \Illuminate\Contracts\Auth\Authenticatable $user
     * @param int $serverId
     * @return \App\Models\Agency\Auth\UserConfig|NULL
     * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
     */
    public function setServer($user, $serverId)
    {
        $server = Server::findOrFail($serverId);

        $config = UserConfig::firstOrNew(['user_id' => $user->id]);

        $config->fill(['server_id' => $server->id])->save();

        return $config;
    }

    /**
     * 个人设置【平台】
     *
     * @param \Illuminate\Contracts\Auth\Authenticatable $user
     * @param string $code
     * @return \App\Models\Agency\Auth\UserConfig|NULL
     * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
     */
    public function setOrg($user, $code)
    {
        $org = Org::where('code', $code)->firstOrFail();

        $config = UserConfig::firstOrNew(['user_id' => $user->id]);

        $config->fill(['org_code' => $org->code])->save();

        return $config;
    }
}
